<?php


namespace app\api\controller;


use addons\epay\library\Collection;
use addons\epay\library\RedirectResponse;
use addons\epay\library\Response;
use addons\epay\library\Service;
use addons\third\model\Third;
use app\common\controller\Api;
use think\Db;
use think\Exception;

class Pay extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    public function payConfirmnew(){
        $order_ids = $this->request->post('package_ids');
        $data = $this->getPayPack($order_ids);

        dump($data);
    }

    // 获取订单支付信息
    public function getPayPack($order_ids){
        $orderList = Db::name('express_package')->where('id','in',$order_ids)->where('status','waitingpay')->select();
        if(!$orderList){
            $this->error = '订单不存在';
            return false;
        }
        $priceSum = $weightSum = $servicePrice = 0;
        foreach ($orderList as $order){
            $weightSum += $order['delivery_weight'];
            $priceSum += $order['delivery_price'];
            $servicePrice += $this->getserviceprice($order['id']);
        }
        $price = $priceSum;
        $discountNow = model('app\api\model\Discount')->where([
            'weight' => ['<',$weightSum]
        ])->order('weight desc')->find();

        //mul乘法  div除法
        if($discountNow){
            $price = bcmul($priceSum,bcdiv($discountNow['discount'],10,2),2);
        }
        //sub 减法
        $discountPrice = bcsub($priceSum,$price,2);
        $discountNext = model('app\api\model\Discount')->where([
            'weight' => ['>',$weightSum]
        ])->order('weight asc')->find();

        $data = [
            'packageList' => $orderList, // 订单信息   r
            'priceSum' => $priceSum, // 订单金额，指的是快递费的金额 r
            'servicePrice' => $servicePrice, // 订单金额
            'weightSum' => $weightSum, // 订单重量(Kg) r
            'price' => $price + $servicePrice, // 支付金额
            'discountPrice' => $discountPrice, // 优惠金额
            'discountNow' => $discountNow, // 当前阶段优惠折扣
            'discountNext' => $discountNext, // 下阶段优惠折扣
        ];
        return $data;
    }


    public function getserviceprice($package_id){
        $list = Db::name('express_order')->where('package_id',$package_id)->select();
        $servicePrice = 0;
        foreach ($list as $value){
            $servicePrice += model('app\api\model\Service')->where('id','in',$value['service_ids'])->sum('price');
        }
        return $servicePrice;
    }


    // 确认支付订单
    public function payConfirm(){

        $order_ids = $this->request->post('package_ids');
        $data = $this->getPayPack($order_ids);
        $this->success('ok',$data);
    }

    // 支付
    public function payment(){
        $order_ids = $this->request->post('package_ids');
        $coupon_id = $this->request->param('coupon_id');
       $coupon_price =  Db::name('coupon')->where('id',$coupon_id)->value('money');

        $data = $this->getPayPack($order_ids);
        $pay = [
            'pay_no' => $this->getPayNo($this->auth->id),
            'user_id' => $this->auth->id,
            'order_ids' => $order_ids,
            'pay_type' => 1,
            'price' => $data['price'],
            'order_price' => $data['priceSum'],
            'discount_price' => $data['discountPrice'],
            'service_price' => $data['servicePrice'],
            'coupon_id'=>$coupon_id,
            'coupon_price'=>$coupon_price
        ];

        $pay['price'] = bcsub($data['price'],$coupon_price,2);
        $result = model('app\api\model\Pay')->allowField(true)->save($pay);
        if($result){
            //创建支付对象
            $config = Service::getConfig('wechat');
            $config['notify_url'] = $this->request->root(true) . '/api/pay/notify';;
            $app = \Yansongda\Pay\Pay::wechat($config);
            $openid = Third::where([
                'user_id' => $this->auth->id,
                'platform' => 'wxapp',
            ])->value('openid');
            $params = [
                'out_trade_no' => $pay['pay_no'],//你的订单号
                'body'         => '支付物流费用',
               'total_fee'    => $pay['price'] * 100 , //单位分

               // 'total_fee'    => 1 , //单位分
                'openid' => $openid,
            ];

            $result = $app->miniapp($params);
            //使用重写的Response类、RedirectResponse、Collection类
            if ($result instanceof \Symfony\Component\HttpFoundation\RedirectResponse) {
                $result = RedirectResponse::create($result->getTargetUrl());
            } elseif ($result instanceof \Symfony\Component\HttpFoundation\Response) {
                $result = Response::create($result->getContent());
            } elseif ($result instanceof \Yansongda\Supports\Collection) {
                $result = Collection::make($result->all());
            }
            $this->success('ok',$result);
        }
        $this->error('支付单创建失败');
    }

    // 支付回调
    public function notify(){
        $pay = Service::checkNotify('wechat');
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        $payOrder = model('app\api\model\Pay')->get([
            'pay_no' => $data['out_trade_no'],
            'pay_state' => '0'
        ]);

        $coupon_id = $payOrder->coupon_id;
        Db::name('coupon')->where('id',$coupon_id)->update([
            'is_used'=>'Y'
        ]);
        if (empty($payOrder)) { // 如果订单不存在
            return true;
            //return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }
        try {
            $payamount = $data['total_fee'] / 100;
            $payOrder->settle($payamount);
            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            return;
        }
        echo $pay->success();
    }

    public function getPayNo($value){
        return substr(time(),-8).substr(substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$value,-8);
    }


}
